package com.bh.extend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.enums.OrderStatus;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.file.ImageUtils;
import com.bh.common.utils.pdf.PdfUtils;
import com.bh.common.utils.spring.SpringUtils;
import com.bh.extend.domain.JcLedSend;
import com.bh.extend.domain.JcOrderBarcode;
import com.bh.extend.mapper.JcLedSendMapper;
import com.bh.extend.mapper.JcOrderBarcodeMapper;
import com.bh.extend.service.IJcOrderBarcodeService;
import com.bh.extend.vo.JcOrderBarcodeImportVo;
import com.bh.extend.vo.JcOrderBarcodePrintVo;
import com.bh.order.domain.JcOrder;
import com.bh.order.mapper.JcOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 条码与商品对应Service业务层处理
 *
 * @author slx
 * @date 2023-03-27
 */

@Service
public class JcOrderBarcodeServiceImpl extends ServiceImpl<JcOrderBarcodeMapper, JcOrderBarcode> implements IJcOrderBarcodeService {
    @Autowired
    private JcOrderBarcodeMapper jcOrderBarcodeMapper;
    @Autowired
    private JcOrderMapper jcOrderMapper;
    @Autowired
    private JcLedSendMapper jcLedSendMapper;

    /**
     * 查询条码与商品对应
     *
     * @param productCode 条码与商品对应主键
     * @return 条码与商品对应
     */
    @Override
    public JcOrderBarcode selectJcOrderBarcodeByProductCode(String productCode) {
        JcOrderBarcode barcode = jcOrderBarcodeMapper.selectJcOrderBarcodeByCode(productCode);
        if (barcode == null) {
            JcOrder order = jcOrderMapper.selectJcOrderByCode(productCode);
            if (order == null) {
                throw new ServiceException("条码与商品对应不存在");
            }
            barcode = jcOrderBarcodeMapper.selectJcOrderBarcodeListByOrderId(order.getId()).get(0);
        }
        if (barcode.getLedOrderId() == null) {
            throw new ServiceException("订单未确认，请先确认订单");
        }
        //两种代码
        return barcode;
    }

    @Override
    public List<JcOrderBarcode> selectJcOrderBarcodeListByOrderId(Long orderId) {
        return jcOrderBarcodeMapper.selectJcOrderBarcodeListByOrderId(orderId);
    }

    @Override
    public List<JcOrderBarcodePrintVo> selectJcOrderBarcodePrintVoListByOrderId(Long orderId) {
        return jcOrderBarcodeMapper.selectJcOrderBarcodePrintVoListByOrderId(orderId);
    }

    @Override
    public List<JcOrderBarcode> selectJcOrderBarcode(Long ledOrderId, String start, String end) {
        return jcOrderBarcodeMapper.selectJcOrderBarcode(ledOrderId, start, end);
    }

    /**
     * 查询条码与商品对应列表
     *
     * @param jcOrderBarcode 条码与商品对应
     * @return 条码与商品对应
     */
    @Override
    public List<JcOrderBarcode> selectJcOrderBarcodeList(JcOrderBarcode jcOrderBarcode) {
        return jcOrderBarcodeMapper.selectJcOrderBarcodeList(jcOrderBarcode);
    }


    @Override
    public List<JcOrderBarcode> selectJcOrderUnloadList(JcOrderBarcode jcOrderBarcode) {
        return jcOrderBarcodeMapper.selectUnloadJcOrderBarcodeList(jcOrderBarcode.getShipmentId(), jcOrderBarcode.getLedOrderId());
    }

    @Override
    public AjaxResult exportPdf(JcOrderBarcode jcOrderBarcode) {
        // 获取数据
        Map<String, Object> data = getData();
        PdfUtils pdfUtils = new PdfUtils();
        return AjaxResult.success(pdfUtils.exportPdfFile("express_sheet", data));
    }

    @Override
    public void printPdf(HttpServletResponse response, JcOrderBarcode jcOrderBarcode) {
        // 获取数据
        Map<String, Object> data = getData();
        PdfUtils pdfUtils = new PdfUtils();
        pdfUtils.exportPdfByte(response, "express_sheet", data);
    }

    private Map<String, Object> getData() {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "John");
        data.put("imagePath", ImageUtils.getResourceImage("static/img/logo.png"));
        data.put("loremIpsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
        return data;
    }

    /**
     * 新增条码与商品对应
     *
     * @param jcOrderBarcode 条码与商品对应
     * @return 结果
     */
    @Override
    public int insertJcOrderBarcode(JcOrderBarcode jcOrderBarcode) {
        return jcOrderBarcodeMapper.insert(jcOrderBarcode);
    }

    @Override
    public int batchInsertJcOrderBarcode(List<JcOrderBarcode> jcOrderBarcodes) {
        return jcOrderBarcodeMapper.batchInsertJcOrderBarcode(jcOrderBarcodes);
    }

    /**
     * 修改条码与商品对应
     *
     * @param jcOrderBarcode 条码与商品对应
     * @return 结果
     */
    @Override
    public int updateJcOrderBarcode(JcOrderBarcode jcOrderBarcode) {
        return jcOrderBarcodeMapper.updateById(jcOrderBarcode);
    }

    @Override
    public int removeJcOrderBarcodePack(String productCode) {
        return jcOrderBarcodeMapper.removeJcOrderBarcodePack(productCode);
    }


    @Override
    public int removeJcOrderBarcodeSend(String productCode) {
        // 查询是否存在其他商品在本 send 中
        JcOrderBarcode barcode = jcOrderBarcodeMapper.selectJcOrderBarcodeByCode(productCode);
        int num = jcOrderBarcodeMapper.removeJcOrderBarcodeSend(productCode);

        JcOrderBarcode query = new JcOrderBarcode();
        query.setSendId(barcode.getSendId());
        List<JcOrderBarcode> jcOrderBarcodes = jcOrderBarcodeMapper.selectJcOrderBarcodeList(query);
        if (jcOrderBarcodes == null || jcOrderBarcodes.size() == 0) {
            //删除加入的 ledId
            JcLedSend send = jcLedSendMapper.selectJcLedSendBySendId(barcode.getSendId());
            send.setLedIds(send.getLedIds().replace(barcode.getLedOrderId().toString(), ""));
            jcLedSendMapper.updateById(send);
        }
        return num;
    }

    /**
     * 批量删除条码与商品对应
     *
     * @param productCodes 需要删除的条码与商品对应主键
     * @return 结果
     */
    @Override
    public int deleteJcOrderBarcodeByProductCodes(String[] productCodes) {
        return jcOrderBarcodeMapper.deleteBatchIds(Arrays.asList(productCodes));
    }

    /**
     * 删除条码与商品对应信息
     *
     * @param productCode 条码与商品对应主键
     * @return 结果
     */
    @Override
    public int deleteJcOrderBarcodeByProductCode(String productCode) {
        return jcOrderBarcodeMapper.deleteById(productCode);
    }


    @Override
    public String importCode(List<JcOrderBarcodeImportVo> codeList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(codeList) || codeList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, List<JcOrderBarcodeImportVo>> listMap = codeList.stream().collect(Collectors.groupingBy(JcOrderBarcodeImportVo::getOrderIdCode));
        for (String key : listMap.keySet()) {
            List<JcOrderBarcodeImportVo> importVos = listMap.get(key);
            // 验证是否存在
            JcOrder order = jcOrderMapper.selectJcOrderByCode(key);
            if (order == null) {
                throw new ServiceException(key + "的订单编码不存在！");
            }
            if (order.getStatus() != OrderStatus.CONFIGRM.getValue()) {
                throw new ServiceException(key + "的订单还未确认！");
            }
            if (importVos.size() != order.getNumber()) {
                throw new ServiceException(order.getCode() + "的产品编码总数不一致，禁止导入！");
            }


            List<JcOrderBarcode> oldOrder = jcOrderBarcodeMapper.selectJcOrderBarcodeListByOrderId(order.getId());
            for (int i = 0; i < importVos.size(); i++) {
                JcOrderBarcodeImportVo importVo = importVos.get(i);
                JcOrderBarcode barcode = oldOrder.get(i);
                barcode.setProductCode(importVo.getProductCode());
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、客户编号 ").append(importVo.getProductCode()).append(" 导入成功");
            }
            SpringUtils.getBean(this.getClass()).updateBatchById(oldOrder);
        }
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public List<String> selectNoUnloadLedIdsByShipmentIdAndOrgId(Long shipmentId, Long orgId) {
        return jcOrderBarcodeMapper.selectNoUnloadLedIdsByShipmentIdAndOrgId(shipmentId, orgId);
    }
}
